
//默认加载数据
$.get('http://t.baitime.cn/wechat/shop/getData',function(datas){
    //转化为json
    var jsons = datas;

    //设置大楼名称
    $('.search-wp div').text(jsons.data.region.region_name);
    $('#regionId').val(jsons.data.region.region_id);


    //判断是否出现评价
/*    if(jsons.data.comment){
        $.get('http://www.buytime.com/wechat/shop/getComment?comment_id='+jsons.data.comment,function(data){
            console.log(data);
        });

        $('.ping').show();




    }else{

    }*/

    //判断是否弹出楼宇列表
    if(jsons.data.region.first==1){
        $('.ahide').show();
    }

    //添加头部本周列表
    var dayInfo = jsons.data.menu;
    var dayLeng = dayInfo.length;
    var dayHtml = '';

    for(var i=0;i<dayLeng;i++){
        var li = i==0?'<li date="'+dayInfo[i].menu_date+'" token="'+dayInfo[i].token+'" class="on">':'<li date="'+dayInfo[i].menu_date+'" token="'+dayInfo[i].token+'">';
        var title = dayInfo[i].menu_title;
        var jieday = title?'<span class="'+(title=='已截止'?'col':'')+'">'+title+'</span>':'<span>'+dayInfo[i].menu_date+'</span>';
        dayHtml+= (li+'<span>'+dayInfo[i].menu_week+'<var></var></span>'+jieday+'<em></em></li>');
    }

    $('.nav-list').html(dayHtml);
    clickDay();

    //显示已售罄和已截止的效果

    var remind = dayInfo[0].remind;

    if(dayInfo[0].remind&&remind.title){
        sellOut(remind.time,remind.title,remind.desc);
    }

    //添加菜品信息
    if(dayInfo[0].goods){
        addGoods(dayInfo[0].goods);
    }

});


//大厦方法
var Build={
    //添加楼宇大厦列表
    addBuilding:function(){
        var _this = this;
        $.get('http://t.baitime.cn/wechat/shop/getRegionList',function(data){
            var html = '';
            var ds = data.data;
            var leng = ds.length;
            for(var i=0;i<leng;i++){
                html+= '<li sid="'+ds[i].region_id+'"><p>'+ds[i].region_name+'</p></li>';
            }
            $('.ahide-wrap').html(html);
            _this.checkBulid();
        });
    },
    //关闭大厦列表
    close:function(){
        $('.ahide-c').find('.quxiao').click(function(){
            $('.ahide').hide();
        });
    },
    //清空输入框方法
    clearInput:function(){
        $('.ahide-c').find('img').click(function(){
            $('#building').val('');
        });
    },
    //选中楼宇方法
    checkBulid:function(){
        $('.ahide-wrap li').each(function(i,e){
            $(e).click(function(){
                var str = $(e).find('p').text();
                $('.ahide').hide();
                $('.search-wp div').text(str);
                $('#regionId').val($(e).attr('sid'));


                $.post('http://t.baitime.cn/wechat/shop/getCurrentData',{region_id:$(e).attr('sid'),menu_date:$('.nav-list').find('.on').attr('date')},function(data){

                    var datas = data;
                    addGoods(datas.data.goods);
                    var remind = datas.data.remind;
                    sellOut(remind.time,remind.title,remind.desc);
                });
            });
        });
    },
    //显示大厦
    showBulid:function(){
        $('.search-wp').click(function(){
            $('.ahide').show();
        });
    },
    //输入选择
    inputFun:function(){
        var _this = this;
        //$("#building").bind('input propertychange',function(){
        $("#building").bind('input propertychange',function(){
            var val = $(this).val();
            console.log(val);
            $.post('http://t.baitime.cn/wechat/shop/getRegionList',{keyword:val},function(data){
                var html = '';
                var ds = data.data;
                var leng = ds.length;
                for(var i=0;i<leng;i++){
                    html+= '<li sid="'+ds[i].region_id+'"><p>'+ds[i].region_name+'</p></li>';
                }
                $('.ahide-wrap').html(html);
                _this.checkBulid();
            });
        });
    },
    //初始化方法
    init:function(){
        this.showBulid();
        this.inputFun();
        this.addBuilding();
        this.close();
        this.clearInput();
    }
};

//初始化大厦方法
Build.init();


var timmer;

function timerFun(num){
    var g = Math.floor(num / 3600);
    var e = Math.floor((num - g * 3600) / 60);
    var f = (num - g * 3600) % 60;
    $('.tips-timer span').eq(0).text(g);
    $('.tips-timer span').eq(1).text(e);
    $('.tips-timer span').eq(2).text(f);
}

//显示已售罄和已截止的效果
function sellOut(time,title,tips){

    if(time){
        $('#sellout').hide();
        $('.yiding-wp').hide();
        $('#selling').show();
        $('.tips-tit').text(title);

        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;

        var cuo = time-timestamp;

        timerFun(cuo);

        timmer = setInterval(function(){
            timerFun(cuo);
            cuo--;
        },1000);
    }else{
        clearInterval(timmer);
        if(title&&tips){
            $('#sellout').show();
            $('#selling').hide();
            $('.yiding-wp').hide();
            $('.tips-all').text(title);
        }else{

            $('.yiding-wp').css({'display':'flex'});
            $('#sellout').hide();
            $('#selling').hide();
        }

    }
    $('.tips-gowp').find('span').text(tips);
}


//添加菜品信息
function addGoods(goods){
    var list = '';

    var leng = goods.length||0;
    for(var i=0;i<leng;i++){
        var txt = goods[i].goods_storage>0?'<li caiid="'+goods[i].goods_id+'" total="'+goods[i].goods_storage+'"><div class="img-wp"><img onclick="caiDeatil('+goods[i].goods_id+')" src="'+goods[i].goods_image+'" /><span class="surplus" style="display:'+(goods[i].goods_storage<10?'block':'none')+'">剩余<em id="surplus">'+goods[i].goods_storage+'</em>份</span></div>':'<li class="qing"><div class="img-wp"><img src="'+goods[i].goods_image+'" class="gray" /><span class="btn">售罄</span></div>';
        list+=(txt+'<div class="act-wp"><p>'+goods[i].goods_name+'</p><div class="add-cont" goodid="'+goods[i].goods_id+'"><span onclick="Car.jianDan(this)"></span><em>0</em><span onclick="Car.addDan(this)"></span></div></div><div class="jia-con"><div class="ml"><h4 class="package-tit">套餐包括:</h4><p class="package-cont">'+goods[i].goods_combo+'</p></div><div class="jia-r"><p><span>菜品原价:</span><em class="line">'+goods[i].market_price+'元</em></p><p><span>抢&nbsp;&nbsp;购&nbsp;&nbsp;价:</span><em class="hot">'+goods[i].shop_price+'</em>元</p></div></div><p class="bar-tit">越早下单越优惠</p><div class="kuai"><img src="'+goods[i].store_logo+'" ><p>'+goods[i].store_slogan+'</p></div></li>');
    }

    $('.cai-list').html(list);

}

//点击菜品图片出现详情
function caiDeatil(id){
    $('.caix').show();
    $.get('http://t.baitime.cn/wechat/shop/getGoodsDetal?goods_id='+id,function(a){
        var datas = JSON.parse(a).data;
        $('.cai-detail').attr('ids',datas.goods_id);
        $('.cai-detail').find('.img-wp').find('img').attr('src',datas.goods_image);
        $('.cai-d-tit').text(datas.goods_name);
        $('.cai-biao').find('p').text(datas.goods_combo);

        $('.can-edit').html(datas.goods_content);
    });

    $('.cai-detail-close').click(function(){
        $('.caix').hide();
    });
}

//点击周几显示内容
function clickDay(){
    $('.nav-list li').each(function(Index,Element){
        $(Element).click(function(){

            var txt = $(this).attr('date');

            $('.nav-list li').removeClass('on');
            $(this).addClass('on');
            var val = $('#regionId').val();
            $.post('http://t.baitime.cn/wechat/shop/getCurrentData',{region_id:val,menu_date:txt},function(data){

                var datas = data;
                addGoods(datas.data.goods);
                var remind = datas.data.remind;
                sellOut(remind.time,remind.title,remind.desc);
            });
        });
    });
}


//购物车操作
var Car = {
    //单品添加效果
    addDan:function(a){
        if(!$(a).parents('li').hasClass('qing')){
            var n = parseInt($(a).parents('li').attr('total'));
            if(n>0){
                $(a).parents('li').attr('total',n-1);

                $('#surplus').text(n-1);
                n-1>=10?$('.surplus').hide():$('.surplus').show();

                var prevTxt = parseInt($(a).prev().text());
                var num = prevTxt+1;
                $(a).prev().text(num);
                var caiName = $(a).parent().prev().text();
                var id = $(a).parent().attr('goodid');
                var tokens = $('.nav-list').find('.on').attr('token');
                var dates = $('.nav-list').find('.on').attr('date');
                var txts = $('.nav-list').find('.on').find('span').eq(0).text();

                this.setNum(caiName,num,tokens,dates,txts,id,n);
            }else{
                alert('暂无存货');
            }

        }

    },
    //单品减少效果
    jianDan:function(a){
        if(!$(a).parents('li').hasClass('qing')) {
            var n = parseInt($(a).parents('li').attr('total'));
            $(a).parents('li').attr('total',n+1);

            $('#surplus').text(n+1);
            n+1>=10?$('.surplus').hide():$('.surplus').show();

            var prevTxt = parseInt($(a).next().text());
            var num = prevTxt > 0 ? prevTxt - 1 : 0;
            $(a).next().text(num);
            var caiName = $(a).parent().prev().text();
            var id = $(a).parent().attr('goodid');
            var tokens = $('.nav-list').find('.on').attr('token');
            var dates = $('.nav-list').find('.on').attr('date');
            var txts = $('.nav-list').find('.on').find('span').eq(0).text();
            this.setNum(caiName,num,tokens,dates,txts,id,n+1);
        }
    },
    //购物车单列表添加数据，参数为 name:菜品名, n:点菜数量，token，date:12月8日,week：周三,goodsid,total:库存
    setNum:function(name,n,token,date,week,goodsid,total){
        var dt = $('.car-list').find('dt[token='+token+']');
        var dds = $('.car-list').find('dd[goodsid='+goodsid+']');
        var dd = '<dd token="'+token+'" goodsid="'+goodsid+'"><p>'+name+'</p><div class="add-cont"><span></span><em>'+n+'</em><span></span></div></dd>';

        if(n==0){
            dds.remove();
            if(dt.nextUntil('dt').length==0){
                dt.remove();
            }
        }else{
            if(dt.length>0){
                dds.length>0?dds.find('em').text(n):dt.after(dd);
            }else{
                var dtHtml = '<dt token="'+token+'" date="'+date+'" week="'+week+'"><span></span>'+week+' '+date+'</dt>';
                $('.car-list').append(dtHtml+dd);
            }
        }

        this.carAdd(goodsid);
    },
    //购物车内加减法
    carAdd:function(id){

        $('.car-list .add-cont').each(function(i,e){
            $(e).find('span').eq(0).unbind();
            $(e).find('span').eq(1).unbind();
            $(e).find('span').eq(0).click(function(){
                var num = parseInt($(this).next().text())-1;
                var n = parseInt($('.cai-list').find('li[caiid='+id+']').attr('total'));
                $(this).next().text(num);
                var t = $(e).parent().attr('token');
                if(num==0){
                    $(e).parent('dd').remove();
                   if($('.car-list').find('dd[token='+t+']').length==0){
                       $('.car-list').find('dt[token='+t+']').remove();
                    }
                }

                $('.cai-list').find('li[caiid='+id+']').attr('total',n+1);
                $('.cai-list').find('li[caiid='+id+']').find('.add-cont').find('em').text(num);

                $('#surplus').text(n+1);
                n+1>=10?$('.surplus').hide():$('.surplus').show();

            });
            $(e).find('span').eq(1).click(function(){
                var n = parseInt($('.cai-list').find('li[caiid='+id+']').attr('total'));
                var num = parseInt($(this).prev().text())+1;
                if(n>0){
                    $(this).prev().text(parseInt($(this).prev().text())+1);
                    $('.cai-list').find('li[caiid='+id+']').attr('total',n-1);
                    $('.cai-list').find('li[caiid='+id+']').find('.add-cont').find('em').text(num);

                    $('#surplus').text(n-1);
                    n-1>=10?$('.surplus').hide():$('.surplus').show();
                }else{
                    alert('库存不足');
                }
            });
        });
    }
};


//点击购物车
$('.car').click(function(){
    $('.car-bg').show();
    $('.car-wp').show();
});
//关闭购物列表
$('.car-wp .close').click(function(){
    $('.car-bg').hide();
    $('.car-wp').hide();
});

//点击结算
$('.car-btns').click(function(){
    var obj = {};
    obj.region = {
        region_id:$('#regionId').val(),
        region_name:$('.search-wp').find('div').text()
    };

    obj.data = [];

    $('.car-list dt').each(function(i,e){
        var act = {};

        act.menu_date = $(e).attr('date');
        act.menu_week = $(e).attr('week');
        act.token = $(e).attr('token');
        act.goods = [];

        $(e).nextUntil('dt').each(function(m,n){
            var goods = {};
            goods.goods_id = $(n).attr('goodsid');
            goods.goods_num = $(n).find('em').text();

            act.goods.push(goods);
        });

        obj.data.push(act);

    });

    if($('.car-list dt').length<1){
        alert('请选择菜品');
    }else{
        $.post('http://t.baitime.cn/wechat/shop/submitCart',{cart:obj},function(data){
            if(data.msg=='ok'){
                $('.jiesuan-wp').show();
                subOrder(data.data);
                $('.jiesuan-close').click(function(){$('.jiesuan-wp').hide();});
            }else{
                alert(data.msg);
            }
        });
    }


});

/* 支付验证 */
function IsChinese(name) {
    var str = $.trim($(name).val());
    if(str == '') {
        alert("对不起，姓名不能为空!");
        return false;
    }else{
        return true;
    }
}
function IsPhone(name) {
    var str = $(name).val();
    var reg =/^1[3,4,5,7,8]\d{9}$/; //是不是手机号码
    if(!reg.test(str)) {
        alert("对不起，您输入的手机号码不正确!");
        return false;
    }else{
        return true;
    }
}
function IsAddress(name) {
    var str = $.trim($(name).val());
    if(str=='') {
        alert("对不起，请您输入地址!");
        return false;
    }else{
        return true;
    }
}
//姓名验证
$("#orderName").on("blur",function(){
    IsChinese("#orderName");
})
//手机号验证
$("#orderPhone").on("blur",function(){
    IsPhone("#orderPhone");
})
//地址标签的隐藏
$("#orderAddress").on("blur",function(){
    IsAddress("#orderAddress");
});

//提交订单操作
function subOrder(obj){
    if(obj.address){
        $('#orderAddress').val(obj.address);
    }

    if(obj.member_name){
        $('#orderName').val(obj.member_name);
    }
    if(obj.member_phone){
        $('#orderPhone').val(obj.member_phone);
    }

    //设置送餐时间
    $('#orderTime').text(obj.deliver_time);
    $('#orderReginName').text(obj.region_name);

    //设置用户点餐列表
    var orderList = '';
    var menu = obj.menu;
    var l = menu.length;
    for(var i=0;i<l;i++){
        orderList += ('<div class="pay-cont-wp" menuId="'+menu[i].menu_id+'"><h3 class="tit">'+menu[i].menu_week+'<br/>('+menu[i].menu_date+')</h3><dl class="list">');
        var goods = menu[i].goods;
        var gl = goods.length;
        for(var c=0;c<gl;c++){
            orderList += ('<dd><p>'+goods[c].goods_name+'</p><span>x'+goods[c].goods_num+'</span></dd>');
        }
        orderList += ('</dl><span class="pase">'+menu[i].goods_price+'元</span></div>');
    }
    $('#orderGoods').html(orderList);

    $('#orderTotal').text(obj.goods_amount+'元');
    $('#orderDiscount').text('-'+obj.goods_count+'元');
    $('#orderAmount').text(obj.order_amount+'元');

    //点击支付
    $('.zhi-btn').click(function(){
        if(IsChinese("#orderName")&&IsPhone("#orderPhone")&&IsAddress("#orderAddress")){
            $.ajax({
                url: "{:C('SITE_URL')}wechat/index/submitOrder",
                dataType: "json",
                data: {
                    "region_id": obj.region_id,
                    "member_name": $("#orderName").val(),
                    "member_phone": $("#orderPhone").val(),
                    "region_name": obj.region_name,
                    "address": $("#orderAddress").val()
                },
                type: "POST",
                beforeSend: function() { alert("订单支付中"); },
                success: function(data) {
                    if(data.code == 0){
                        callpay(data.data);
                    } else if (data.code == 999){
                        window.location = "{:C('SITE_URL')}wechat/index/finnshedOrder";
                    } else {
                        alert(data.msg);
                    }
                },
                error: function() {
                    alert("订单支付失败，请重新支付");
                }
            });
        }
    });



}

function jsApiCall(data){
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        data,
        function(res){
            //WeixinJSBridge.log(res.err_msg);
            //alert(res.err_code+res.err_desc+res.err_msg);
            if(res.err_msg == "get_brand_wcpay_request:ok"){
                window.location = "{:C('SITE_URL')}wechat/index/finnshedOrder";
            } else {
                alert("支付取消，请重新支付");
            }
        }
    );
}

function callpay(data){
    if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
        }else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
        }
    }else{
        jsApiCall(data);
    }
}
//关闭点评框
/*
$('.ping-tit span').click(function(){
    $('.ping').hide();
});


//选中黑心
$('.ping-xin span').each(function(i,e){
    $(e).click(function(){
        var val = 0;
        if($(e).hasClass('on')){
            $('.ping-xin span').each(function(c,m){
                if(c>=i){
                    $(m).removeClass('on');
                }
            });
            val = i;
        }else{
            $('.ping-xin span').removeClass('on');
            $('.ping-xin span').each(function(c,m){
                if(c<=i){
                    $(m).addClass('on');
                }
            });

            val = i+1;
        }

        $('#xin').val(val);
    });
});

 */